package com.koron.bean.util;

import com.koron.bean.enums.OperationEnum;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Optional;

/**
 * 获取session数据即拿到当前登录用户信息
 *
 * @author QL
 * @date 2020/11/5 16:28
 */
public class ServletUtils {
    public static ServletRequestAttributes getRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    public static HttpServletRequest getRequest() {
        return Optional.ofNullable(getRequestAttributes()).map(ServletRequestAttributes::getRequest).orElse(null);
    }

    public static HttpSession getSession() {
        return Optional.ofNullable(getRequest()).map(HttpServletRequest::getSession).orElse(null);
    }

    // 获取请求方法类型名
    public static String getMethodName() {
        return Optional.ofNullable(getRequest()).map(HttpServletRequest::getMethod).map(e -> OperationEnum.valueOf(e).getValue()).orElse(null);
    }
}
